package com.rh.bmw4s.ui;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.CategoryDetailAdapter;
import com.rh.bmw4s.adapter.CatergoryAdapter;
import com.rh.bmw4s.adapter.GridAdapter;
import com.rh.bmw4s.bean.BaseBean;
import com.rh.bmw4s.bean.BrandBean;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.inter.OpenItemIner;
import com.rh.bmw4s.utills.DealResult;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.view.fragdialog.ParamListDialog;
import com.rh.bmw4s.view.SlideBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 三级选择车型界面
 */
public class SelectCarTypeActivity extends BaseActivity implements OpenItemIner {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.recy_selecttype_content)
    LRecyclerView recyContent;
    @BindView(R.id.slideBar_selecttype)
    SlideBar slideBar;
    @BindView(R.id.tv_back1)
    TextView tvBack1;
    @BindView(R.id.recy_car_list)
    LRecyclerView recyCarList;
    @BindView(R.id.drawer_selecttype)
    DrawerLayout drawerLayout;

    //第一层
    private CatergoryAdapter mAdapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;

    //第二层
    private CategoryDetailAdapter carListAdapter;
    private LRecyclerViewAdapter lrecyclerViewAdapter2;

    //热门车型
    private LRecyclerView recyclerViewGrid;
    private GridAdapter gridAdapter;

    //车辆第一个字母
    private HashMap<String, Integer> maps = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_cartype);
        ButterKnife.bind(this);
        initView();
        initContentRecy();
        initDetailView();
    }


    private void initView() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("选择车型");
        slideBar.setOnTouchLetterListenner(new TouchLetterListenner());
    }

    //第一层
    private void initContentRecy() {
        DialogUtils.showProgressDlg(SelectCarTypeActivity.this, "努力加载中......");

        recyContent.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new CatergoryAdapter(SelectCarTypeActivity.this);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyContent.setAdapter(lRecyclerViewAdapter);
        //添加热门车型头部
        CommonHeader header = new CommonHeader(SelectCarTypeActivity.this, R.layout.head_category_grid);
        initContentHead(header);
        lRecyclerViewAdapter.addHeaderView(header);

        DividerDecoration divider = new DividerDecoration.Builder(SelectCarTypeActivity.this)
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        recyContent.addItemDecoration(divider);
        recyContent.setLoadMoreEnabled(false);
        recyContent.setPullRefreshEnabled(false);
        getContentData();

    }

    /**
     * 获取第一层数据
     */
    private void getContentData() {
        OkGo.<String>post(Constant.SELECTION)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<BrandBean> bean = DealResult.getInstace().dealData(SelectCarTypeActivity.this,
                                response, new TypeToken<BaseBean<BrandBean>>() {
                                }.getType());
                        if (bean == null) {
                            return;
                        }
                        List<BrandBean> beans = bean.getDatas();
                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(SelectCarTypeActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setDatas(List<BrandBean> beans) {
        BrandBean.BrandsBean brandsBean = new BrandBean.BrandsBean();
        List<BrandBean.BrandsBean> brandsBeanList = new ArrayList<>();
        brandsBean.setModel_name("不限品牌");
        brandsBeanList.add(brandsBean);
        BrandBean bean = new BrandBean();
        bean.setBrands(brandsBeanList);
        bean.setLetters("#");
        beans.add(0, bean);
        for (int i = 0; i < beans.size(); i++) {
            maps.put(beans.get(i).getLetters(), i);
        }
        mAdapter.setDataList(beans);
        recyContent.refreshComplete(beans.size());
    }


    /**
     * 第二层
     */
    private void initDetailView() {
        recyCarList.setLayoutManager(new LinearLayoutManager(SelectCarTypeActivity.this));
        carListAdapter = new CategoryDetailAdapter(SelectCarTypeActivity.this);
        lrecyclerViewAdapter2 = new LRecyclerViewAdapter(carListAdapter);
        recyCarList.setAdapter(lrecyclerViewAdapter2);
        DividerDecoration divider = new DividerDecoration.Builder(SelectCarTypeActivity.this)
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        recyCarList.addItemDecoration(divider);
        recyCarList.setLoadMoreEnabled(false);
        recyCarList.setPullRefreshEnabled(false);
        recyCarList.refresh();
    }


    /**
     * 添加热门品牌
     */
    private void initContentHead(CommonHeader header) {
        recyclerViewGrid = header.findViewById(R.id.recyclerView_grid);
        recyclerViewGrid.setLayoutManager(new GridLayoutManager(this, 4));

        gridAdapter = new GridAdapter(SelectCarTypeActivity.this);
        LRecyclerViewAdapter gridLrecyclerViewAdapter = new LRecyclerViewAdapter(gridAdapter);
        recyclerViewGrid.setAdapter(gridLrecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(SelectCarTypeActivity.this)
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        recyclerViewGrid.addItemDecoration(divider);
        recyclerViewGrid.setLoadMoreEnabled(false);
        recyclerViewGrid.setPullRefreshEnabled(false);
        getHotBrandsDatas();
        //热门车型点击事件
        gridAdapter.setHotCarTypeItemListener(new GridAdapter.HotCarTypeItemListener() {
            @Override
            public void onHotTypeItemListener(int id) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                carListAdapter.clear();
                drawerLayout.openDrawer(Gravity.RIGHT);
                getCarListDatas(id);
            }
        });
    }

    /**
     * 获取热门车型数据
     */
    private void getHotBrandsDatas() {
        OkGo.<String>post(Constant.HOT_BRANDS)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        BaseBean<BrandBean.BrandsBean> bean = DealResult.getInstace().dealData(SelectCarTypeActivity.this,
                                response, new TypeToken<BaseBean<BrandBean.BrandsBean>>() {
                                }.getType());
                        if (bean == null) {
                            return;
                        }
                        List<BrandBean.BrandsBean> beans = bean.getDatas();
                        gridAdapter.addAll(beans);
                        recyclerViewGrid.refreshComplete(beans.size());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(SelectCarTypeActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }


    //------------------------点击事件---------------------------------------
    @Override
    public void itemClick(int id) {
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        carListAdapter.clear();
        drawerLayout.openDrawer(Gravity.RIGHT);
        getCarListDatas(id);
    }

    private ParamListDialog dialog = null;

    @Override
    public void itemDetailClick(BrandBean.BrandsBean bean) {
//        Intent i = new Intent();
//        i.putExtra("bean", bean);
//        this.setResult(1, i);
//        this.finish();
        dialog = new ParamListDialog();
        Bundle bundle = new Bundle();
        bundle.putInt("carid", bean.getId());
        dialog.setArguments(bundle);
        dialog.show(getFragmentManager(), "ParamListDialog");
        dialog.setSlideDialogOnClick(new ParamListDialog.slideDialogOnClick() {
            @Override
            public void closeDialog() {
                dialog.dismiss();
            }
        });
    }
//------------------------点击事件---------------------------------------

    /**
     * 获取第二层数据
     */
    private void getCarListDatas(int id) {
        OkGo.<String>post(Constant.SELECTION_DETAIL)
                .tag(this)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<BrandBean> bean = DealResult.getInstace().dealData(SelectCarTypeActivity.this,
                                response, new TypeToken<BaseBean<BrandBean>>() {
                                }.getType());
                        List<BrandBean> beans = bean.getDatas();
                        if (beans == null) {
                            return;
                        }
                        setDetailDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(SelectCarTypeActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    public void setDetailDatas(List<BrandBean> beans) {
        BrandBean.BrandsBean brandsBean = new BrandBean.BrandsBean();
        List<BrandBean.BrandsBean> brandsBeanList = new ArrayList<>();
        brandsBean.setModel_name("不限车系");
        brandsBeanList.add(brandsBean);
        BrandBean bean = new BrandBean();
        bean.setBrands(brandsBeanList);
        bean.setLetters("不限车系");
        beans.add(0, bean);
        carListAdapter.setDataList(beans);
        recyCarList.refreshComplete(beans.size());
    }

    /**
     * 字母点击事件
     */
    class TouchLetterListenner implements SlideBar.OnTouchLetterListenner {
        @Override
        public void OnTouchLetterChange(MotionEvent event, String str) {
            try {
                int position = maps.get(str);
                Log.d("CCC", position + "");
                ((LinearLayoutManager) recyContent.getLayoutManager()).scrollToPositionWithOffset(position, 0);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_back1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                SelectCarTypeActivity.this.finish();
                break;
            case R.id.tv_back1:
                if (drawerLayout != null) {
                    if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                        drawerLayout.closeDrawers();
                    }
                }
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        SelectCarTypeActivity.this.finish();
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout != null && drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.closeDrawers();
        } else {
            SelectCarTypeActivity.this.finish();
        }

    }


}

